<template>
	<view class="">
		<!-- 自定义导航栏 -->
		<view ref="customNavbarRef" class="customNavbar">
			<custom-navbar :showTitle="true" backgroundColor="transparent" textColor="#ffffff" :showBack="false" :isHomePage="false"></custom-navbar>
		</view>
		<view class="" ref="contentRef">
			<!-- 预定日期 需求：只能预定周五周六-->
			<view class="date-picker">
				<text class="calendar-title">选择预定日期（仅限周五、周六）</text>	
				<view class="date-selector" @click="showCalendar = true">
					<text class="date-label">预约日期：</text>
					<text class="date-value">{{ formatSelectedDate(value) }}</text>
					<image src="https://image.shengxuankj.com/fronts/arrow.png" style="width: 28rpx;height: 28rpx;"/>
				</view>
				<up-calendar
					:show="showCalendar"
					:mode="'single'"
					:customList="customList"
					:round="10"
					:startDate="startDate"
					:endDate="endDate"
					@confirm="onCalendarConfirm"
					@close="showCalendar = false"
				></up-calendar>
			</view>
			<up-cate-tab class="cate-tab" :tabList="cateList" tabKeyName="name" itemKeyName="name" :height="availableHeight">
				<template #pageItem="{ pageItem }" style="width: 100%;">
					<view class="product-item">
						<!-- 商品图片 -->
						<view class="product-image">
							<up-image :src="jsonToArray(pageItem.image)[0]" width="120rpx" height="120rpx" radius="8rpx"></up-image>
						</view>
						<!-- 商品信息 -->
						<view class="product-info">
							<!-- 商品标题 -->
							<view class="product-title">
								<text class="title-text">{{ pageItem.title }}</text>
							</view>
							<!-- 商品描述（可选） -->
							<view class="product-desc" v-if="pageItem.desc">
								<text class="desc-text">{{ pageItem.desc }}</text>
							</view>
							<!-- 价格和数量选择器 -->
							<view class="product-bottom">
								<view class="price-section">
									<text class="price-symbol">￥</text>
									<text class="price-value">{{ pageItem.price }}</text>
								</view>
								<view class="quantity-section">
									<up-number-box 
										v-model="pageItem.quantity" 
										:min="0" 
										:max="99"
										size="small"
										@change="onQuantityChange(pageItem)"
									>
										<template #minus>
											<view class="quantity-btn minus-btn" @click="onDelQuantity(pageItem)">
												<up-icon name="minus-circle-fill" size="24" color="#666"></up-icon>
											</view>
										</template>
										<template #input>
											<text class="quantity-input">{{ pageItem.quantity || 0 }}</text>
										</template>
										<template #plus>
											<view class="quantity-btn plus-btn" @click="onAddQuantity(pageItem)">
												<up-icon name="plus-circle-fill" size="24" color="#f00"></up-icon>
											</view>
										</template>
									</up-number-box>
								</view>
							</view>
						</view>
					</view>
				</template>
			</up-cate-tab>
		</view>
		<view class="submitBar">
			<SubmitTabbar 
				ref="submitBarRef" 
				:currentProduct="currentProduct"
				@addToCart="handleAddToCart"
				@buyNow="handleBuyNow"
				@clearCartList="clearCartListFun"
				@updateCartList="updateCartListFun"
			/>
		</view>
		<!-- 登录弹窗 -->
		<wx-login-popup 
			:show="showLoginPopup"
			@close="onCloseLoginPopup"
			@success="onLoginSuccess" 
		/>
	</view>
</template>

<script lang="ts" setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, onMounted, computed, nextTick, toRaw } from 'vue';
// import SubmitBar from '@/components/submitTabbar/index.vue';
import SubmitTabbar from '../../components/submitTabbar/index.vue'
import CustomNavbar from '@/components/custom-navbar/index';
import { goodsListFun, goodsCateFun, cartListFun, cartAddFun, cartEditFun } from '@/api/port'
import { globalCart } from '@/composables/useCart'
import icon from 'uview-plus/components/u-icon/icon';
import wxLoginPopup from '@/components/wx-login-popup/index.vue'

const jsonToArray = (json: any) => {
	if(json){
		return json.split(',')
	}
}

// 日历组件相关配置
const showCalendar = ref(false)
const value = ref('')
const startDate = ref('')
const endDate = ref('')

// 自定义日期列表（用于标记周五周六可选，其他日期禁用）
const customList = ref([])

// 格式化选中的日期显示
const formatSelectedDate = (dateStr: string) => {
	if (!dateStr) return ''
	const date = new Date(dateStr)
	const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
	const weekDay = weekDays[date.getDay()]
	const month = date.getMonth() + 1
	const day = date.getDate()
	return `${month}月${day}日 ${weekDay}`
}

// 生成自定义日期列表（标记可选和不可选的日期）
const generateCustomList = () => {
	const today = new Date()
	const customDates = []
	
	// 生成未来3个月的日期
	for (let i = 0; i < 90; i++) {
		const currentDate = new Date(today)
		currentDate.setDate(today.getDate() + i)
		
		const year = currentDate.getFullYear()
		const month = String(currentDate.getMonth() + 1).padStart(2, '0')
		const day = String(currentDate.getDate()).padStart(2, '0')
		const dateStr = `${year}-${month}-${day}`
		
		const dayOfWeek = currentDate.getDay()
		const isWeekend = dayOfWeek === 5 || dayOfWeek === 6 // 周五或周六
		
		customDates.push({
			date: dateStr,
			topInfo: isWeekend ? '可预定' : '',
			bottomInfo: isWeekend ? '' : '不可选',
			disabled: true,
			dot: isWeekend
		})
	}
	
	customList.value = customDates
}

// 获取今天的日期并判断是否为周五或周六
const getTodayInfo = () => {
	const today = new Date()
	const dayOfWeek = today.getDay() // 0=周日, 1=周一, ..., 5=周五, 6=周六
	const isWeekend = dayOfWeek === 5 || dayOfWeek === 6 // 周五或周六
	
	return { isWeekend, dayOfWeek }
}

// 设置日历组件的开始和结束日期
const initDatePicker = () => {
	const today = new Date()
	const year = today.getFullYear()
	const month = String(today.getMonth() + 1).padStart(2, '0')
	const day = String(today.getDate()).padStart(2, '0')
	
	// 设置开始日期为今天
	startDate.value = `${year}-${month}-${day}`
	
	// 设置结束日期为3个月后
	const futureDate = new Date(today)
	futureDate.setMonth(today.getMonth() + 3)
	const endYear = futureDate.getFullYear()
	const endMonth = String(futureDate.getMonth() + 1).padStart(2, '0')
	const endDay = String(futureDate.getDate()).padStart(2, '0')
	endDate.value = `${endYear}-${endMonth}-${endDay}`
	
	// 生成自定义日期列表
	generateCustomList()
	
	// 获取今天信息并设置默认值
	const todayInfo = getTodayInfo()
	
	// 如果今天是周五或周六，设置为默认选中日期
	if (todayInfo.isWeekend) {
		value.value = `${year}-${month}-${day}`
	} else {
		// 如果今天不是周五或周六，找到下一个周五作为默认日期
		const nextFriday = new Date(today)
		const daysUntilFriday = (5 - nextFriday.getDay() + 7) % 7 || 7
		nextFriday.setDate(nextFriday.getDate() + daysUntilFriday)
		const nextYear = nextFriday.getFullYear()
		const nextMonth = String(nextFriday.getMonth() + 1).padStart(2, '0')
		const nextDay = String(nextFriday.getDate()).padStart(2, '0')
		value.value = `${nextYear}-${nextMonth}-${nextDay}`
	}
}

// 日历确认事件处理
const onCalendarConfirm = (e: any) => {
	console.log('选择的日期:', e)
	
	// e 可能是数组或字符串，统一处理
	const selectedDate = Array.isArray(e) ? e[0] : e
	
	if (!selectedDate) {
		uni.showToast({
			title: '请选择日期',
			icon: 'none'
		})
		return
	}
	
	// 验证选择的日期是否为周五或周六
	const date = new Date(selectedDate)
	const dayOfWeek = date.getDay()
	
	if (dayOfWeek !== 5 && dayOfWeek !== 6) {
		uni.showToast({
			title: '只能预定周五和周六',
			icon: 'none'
		})
		return
	}
	
	value.value = selectedDate
	showCalendar.value = false
	
	uni.showToast({
		title: `已选择${dayOfWeek === 5 ? '周五' : '周六'}`,
		icon: 'success'
	})
}
// 响应式数据
const customNavbarRef = ref<InstanceType<typeof CustomNavbar>>();
const submitBarRef = ref<InstanceType<typeof SubmitTabbar>>();

const navBarHeight = ref<number>(44);
const windowHeight = ref<number>(0);
const submitBarHeight = ref<number>(0);

// 计算导航栏总高度
const navbarTotalHeight = computed((): number => {
	return navBarHeight.value;
});

// 计算可视高度减去导航栏高度
const availableHeight = computed((): number => {
	// console.log(windowHeight.value, navbarTotalHeight.value, submitBarHeight.value, windowHeight.value - navbarTotalHeight.value - submitBarHeight.value);
	return windowHeight.value - navbarTotalHeight.value - submitBarHeight.value;
});



// 初始化系统信息
const initSystemInfo = (): void => {
	const systemInfo = uni.getWindowInfo();
	windowHeight.value = systemInfo.windowHeight || 0;
};

// 使用全局购物车
const { addToCart } = globalCart

// 当前选中的商品（用于加入购物车）
const currentProduct = ref<any[]>([])

/**
 * 商品数量变化处理
 * @param item 商品项
 */
const onQuantityChange = async (item: any) => {
	await nextTick()
	console.log('商品数量变化:', item.title, '数量:', item.quantity);
};

/**
 * 增加数量
 * @param item 购物车商品项
 */
const onAddQuantity = async (item: any) => {
	// 判断是否登录
	if(!uni.getStorageSync('token')){
		await getGoodsCate()
		uni.showToast({
			title: '请先登录！',
			icon: 'none',
			dduration: 2000
		})
		return false
	}
  	// 调用添加购物车接口
	await cartAddFun({
		goods_id: item.id,
		num: 1
	})
	console.log('成功调用添加购物车接口:', item.title, '增加数量:', 1)

	// 刷新购物车数据
	await getCartList()
}

/**
 * 删除数量
 * @param item 购物车商品项
 */
const onDelQuantity = async (item: any) => {
	console.log('删除数量:', item)
	if(item.quantity <= 0){
		return
	}
	await nextTick()
	let obj = cartList.value.find((item2: any) => item2.goods_id === item.id)
	// return
  	// 调用添加购物车接口
	await cartEditFun({
		id: obj.id,
		num: obj.num - 1
	})

	// 刷新购物车数据
	await getCartList()
}

/**
 * 处理加入购物车事件
 * @param product 商品信息
 */
const handleAddToCart = (product: any) => {
	console.log('加入购物车:', product)
	// 调用购物车的添加方法
	if (product && product.quantity > 0) {
		globalCart.addToCart({
			id: product.id,
			title: product.title,
			price: product.price,
			image: product.image,
			desc: product.desc
		}, product.quantity)
		uni.showToast({
			title: '已加入购物车',
			icon: 'success'
		})
	} else {
		uni.showToast({
			title: '请先选择商品数量',
			icon: 'none'
		})
	}
}

/**
 * 处理立即购买事件
 * @param productIds 商品ID字符串
 */
const handleBuyNow = (productIds: string) => {
	console.log('立即购买商品ID:', productIds)
	// 检查是否选择了日期
	if (!value.value) {
		uni.showToast({
			title: '请选择日期',
			icon: 'none'
		})
		return
	}
	// 检查是否选择了商品
	if (currentProduct.value.length === 0) {
		uni.showToast({
			title: '请选择商品',
			icon: 'none'
		})
		return
	}
	// 检查所选日期是否是周五或周六
	const date = new Date(value.value)
	const dayOfWeek = date.getDay()
	if (dayOfWeek !== 5 && dayOfWeek !== 6) {
		uni.showToast({
			title: '只能预定周五和周六',
			icon: 'none'
		})
		return
	}
	uni.navigateTo({
		url: `/subpackage/shopBook/shopBook?cartData=${encodeURIComponent(JSON.stringify(currentProduct.value))}`
	})
}

const clearCartListFun = async () => {
	await getCartList()
	await getGoodsCate()
}

/**
 * 分类列表（原始接口返回）
 */
const cateList = ref<any[]>([])
/**
 * 获取分类并为每个分类填充对应的 children 商品数组
 * 逻辑：
 * 1) 先拉取分类集合
 * 2) 使用 Promise.all 并发拉取每个分类下的商品
 * 3) 将最终结果同步到 cateList 与 tabList（组件直接使用）
 */
const getGoodsCate = async (): Promise<void> => {
	try {
		let res = await goodsCateFun({})
		if (res && res.code === 1) {
			cateList.value = res.data
			cateList.value.forEach(async (item: any) => {
				let result = await goodsListFun({
					page: 1,
					limit: 999,
					cate_id: item.id,
				})
				let list = result.data.list
				list.forEach((item: any) => {
					let obj = cartList.value.find((item2: any) => item2.goods_id === item.id)
					if(obj){	
						item.quantity = obj.num
					}else{
						item.quantity = 0
					}
				})
				item.children = list
			})
		}
	} catch (e) {
		console.error('获取分类失败:', e)
	}
}
// 登录弹窗
const showLoginPopup = ref(false)
/**
 * 购物车列表
 */
const cartList = ref<any[]>([])
/**
 * 获取购物车列表
 */
const getCartList = async () => {
	let res = await cartListFun({})
	if (res && res.code === 1) {
		cartList.value = res.data
		currentProduct.value = res.data
		globalCart.cartItems.value = res.data
	} else if (res && res.code === 401) {
		showLoginPopup.value = true
	}
}


// 关闭登录弹窗
const onCloseLoginPopup = (): void => {
    showLoginPopup.value = false
}

// 登录成功回调
const onLoginSuccess = (e: LoginEvent): void => {
    showLoginPopup.value = false
    // 登录完成后继续预订流程
    getCartList()
}


/**
 * 处理购物车加减回调
 */
const updateCartListFun = async (item: any, type: string) => {
	console.log('购物车数量改变:', item)
	let params = toRaw(item)
	// 使用标签语句来控制嵌套循环的跳出
	outerLoop: for (let item2 of cateList.value) {
		for (let item3 of item2.children) {
			if (item3.id == params.goods_id) {
				item3.quantity = type == 'minus' ? params.num - 1 : type == 'plus' ? params.num + 1 : 0
				break outerLoop // 找到匹配项后跳出整个嵌套循环
			}
		}
	}
	// await nextTick()
	// 改变 goods 的数量
	// if(type == 'minus'){
	// 	item.quantity--
	// }
	// if(type == 'plus'){
	// 	item.quantity++
	// }
}


onLoad(async ()=>{
	initSystemInfo();
	// 初始化日期选择器
	initDatePicker();
	// 首次加载分类与对应商品
	
	await nextTick(() => {
		let timer = setTimeout(() => {
			// 直接使用uni全局对象
			const query = uni.createSelectorQuery();
			query
				.select('.customNavbar')
				.boundingClientRect((data) => {
					if (data) {
						navBarHeight.value = data.height;
					}
				})
				.exec();
			query
				.select('.submitBar')
				.boundingClientRect((data) => {
					if (data) {
						submitBarHeight.value = data.height;
					}
				})
				.exec();
			clearTimeout(timer);
		}, 500);
		
	});
	
	await getGoodsCate();
})
onShow(async ()=>{
	await getCartList()
})

// 页面挂载时初始化
onMounted(async () => {
	
});
</script>

<style lang="scss" scoped>
// 日期选择器样式
.date-picker {
	padding: 30rpx;
	background-color: #fff;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	margin-bottom: 20rpx;
	margin: 20rpx;
	.calendar-title{
		font-size: 30rpx;
		color: #333;
		font-weight: 500;
	}
	.date-selector {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		// background-color: #f8f9fa;
		border-radius: 12rpx;
		// border: 2rpx solid #e9ecef;
		cursor: pointer;
		transition: all 0.3s ease;
		
		// &:hover {
		// 	border-color: #007aff;
		// 	background-color: #f0f8ff;
		// }
		
		.date-label {
			font-size: 30rpx;
			color: #333;
			font-weight: 500;
		}
		
		.date-value {
			flex: 1;
			font-size: 30rpx;
			color: #007aff;
			font-weight: 600;
			margin-left: 10rpx;
		}
		
	}
}

.cate-tab {
	// height: calc(100vh - 150px);
	// /* #ifdef H5 */
	// height: calc(100vh - 150px - var(--window-top));
	// /* #endif */
}

.submitBar {
	width: 100%;
	height: 100rpx;
}

// 商品项样式
.product-item {
	width: 100%;
	display: flex;
	flex-direction: row;
	align-items: flex-start;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	background-color: #fff;
	gap: 24rpx;

	// 商品图片
	.product-image {
		flex-shrink: 0;
	}

	// 商品信息
	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 120rpx;

		// 商品标题
		.product-title {
			margin-bottom: 8rpx;

			.title-text {
				font-size: 28rpx;
				font-weight: 500;
				color: #333;
				line-height: 1.4;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}

		// 商品描述
		.product-desc {
			margin-bottom: 8rpx;

			.desc-text {
				font-size: 24rpx;
				color: #999;
				line-height: 1.3;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 1;
				overflow: hidden;
			}
		}

		// 底部价格和数量
		.product-bottom {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: auto;

			// 价格区域
			.price-section {
				display: flex;
				align-items: baseline;

				.price-symbol {
					font-size: 24rpx;
					color: #ff4757;
					font-weight: 500;
				}

				.price-value {
					font-size: 32rpx;
					color: #ff4757;
					font-weight: 600;
					margin-left: 2rpx;
				}
			}

			// 数量选择区域
			.quantity-section {
				margin-left: 20rpx;
				.quantity-btn {
					width: 48rpx;
					height: 48rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 8rpx;

					// &.minus-btn {
					// 	background-color: #f8f8f8;
					// 	border: 1rpx solid #e8e8e8;
					// }

					// &.plus-btn {
					// 	background-color: #ff4757;
					// 	border: 1rpx solid #ff4757;
					// }
				}

				.quantity-input {
					width: 60rpx;
					height: 48rpx;
					text-align: center;
					line-height: 48rpx;
					font-size: 26rpx;
					color: #333;
					// background-color: #f8f8f8;
					// border: 1rpx solid #e8e8e8;
					// border-left: none;
					// border-right: none;
				}
			}
		}
	}
}
.cate-tab>view {
	width: 100%;
}
:deep(.item-container){
	width: 100%;
}
:deep(.item-container>view){
	width: 100%;
}
</style>
